<script setup>
import MyNav from "@/components/MyNav.vue";
import MyHead from "@/components/MyHead.vue";
import MyTable from "@/components/MyTable.vue";
import {onMounted, ref, shallowReactive, shallowRef} from "vue";
import {dateFormat, myRemove, myPage, myRemoveBatch, genderFormat, elConfirm, getResponseData} from "@/utils";
import {pageApi, dimSelectApi, removeApi, removeBatchApi, resetPasswordApi, getRolesApi} from "@/api/EmpAPI";
import MyPager from "@/components/MyPager.vue";
import MyList from "@/components/MyList.vue";
import {excelApi} from "@/api/axios";
import router from "@/router";
import {MINIO_HOST} from "@/const";
import MyUploader from "@/components/MyUploader.vue";
import {ElMessage} from "element-plus";

// 表格记录 + 主键数组 + 分页信息 + 详情抽屉 + 详情列表 + 登录账户
let records = ref();
let ids = [];
let pageInfo = shallowReactive({'pageNum': 1, 'pageSize': 5, 'fn': page});
let detailDrawer = shallowRef();
let detailItems = ref();
let roleDrawer = shallowRef();
let empRealName = shallowRef();
let currentId;
let loginEmp = JSON.parse(sessionStorage.getItem('loginEmp'));

/* ==================== 分页查询 ==================== */
async function page(pageNum = pageInfo['pageNum'],
                    pageSize = pageInfo['pageSize']) {
  let config = {
    'api': pageApi,
    'params': {'pageNum': pageNum, 'pageSize': pageSize},
    'records': records,
    'pageInfo': pageInfo
  }

  // 搜索员工名
  if (empRealName.value) {
    config['params']['keyword'] = empRealName.value;
    config['api'] = dimSelectApi;
  }

  // 发送分页请求
  await myPage(config);
}

/* ==================== 单条修改 ==================== */
function update(record) {
  sessionStorage.setItem('emp', JSON.stringify(record));
  router.push('/EmpUpdate');
}


/* ==================== 单条删除 ==================== */
async function remove(record) {
  await myRemove({
    'id': record['id'],
    'api': removeApi,
    'fn': page
  });
}

/* ==================== 批量删除 ==================== */
async function removeBatch() {
  await myRemoveBatch({
    'ids': ids,
    'api': removeBatchApi,
    'fn': page
  });
}

/* ==================== 搜索员工名 ==================== */
function pageByRealName(record) {
  // 仅当输入框有值，或者当前处于按条件分页状态时，发送分页请求
  if (record || empRealName.value) {
    empRealName.value = record;
    page();
  }
}

/* ==================== 查看详情 ==================== */
function detail(record) {
  detailItems.value = [
    {
      'label': '员工头像', 'value': record['avatar'], 'type': 'img',
      minio: url => MINIO_HOST + '/avatar/' + url
    },
    {'label': '登录账号', 'value': record['username']},
    {'label': '手机号码', 'value': record['phone']},
    {'label': '微信号码', 'value': record['wechat']},
    {'label': '电子邮件', 'value': record['email']},
    {'label': '员工性别', 'value': record['gender'], 'format': genderFormat},
    {'label': '员工年龄', 'value': record['age']},
    {'label': '所在省份', 'value': record['province']},
    {'label': '详细地址', 'value': record['address']},
    {'label': '真实姓名', 'value': record['realname']},
    {'label': '身份证号', 'value': record['idcard']},
    {'label': '所在部门', 'value': record['dept'] ? record['dept']['title'] : '暂未分配部门'},
    {'label': '入职日期', 'value': record['hiredate'], 'format': dateFormat},
    {'label': '创建时间', 'value': record['created'], 'format': dateFormat},
    {'label': '修改时间', 'value': record['updated'], 'format': dateFormat},
    {'label': '员工描述', 'value': record['info'], 'type': 'card'},
  ];
  detailDrawer.value = true;
}

/* ==================== 上传头像 ==================== */
let uploadDrawer = shallowRef();
let uploadUrl = shallowRef();
function upload(record) {
  uploadDrawer.value = true;
  currentId = record['id'];
  uploadUrl.value = 'http://localhost:8101/api/v1/emp/uploadAvatar?id=' + record['id'];
}

function uploadSuccess() {
  uploadDrawer.value = false;
  if (loginEmp['id'] === currentId){
    ElMessage.warning('修改了当前用户信息，请重新登录');
    setTimeout(() => router.push('/'), 1000);
  }else {
    page();
  }

}

/* ==================== 重置密码 ==================== */
async function resetPassword(record) {
  console.log(record)
  // 危险操作保护
  if (!await elConfirm('是否要重置密码？')) return;

  let res = await resetPasswordApi(record['id']);
  let data = getResponseData(res);
  if (data) {
    ElMessage.success(`密码重置为${data}`);
    // 若重置的是当前登录的员工，则跳入登录页面
    if (loginEmp['id'] === record['id']) {
      ElMessage.success('重置了当前登录的员工密码，请重新登录！');
      setTimeout(() => router.push('/'), 1000);
    }
    // 否则重新分页
    else {
      await page();
    }
  }
}

/*===================== 角色查看 =======================*/
function toEmpRoles(record){
  router.push({'path': '/EmpRoles', query: {'empId': record['id']}})
}

/* ==================== 加载函数 ==================== */
onMounted(() => page());

</script>

<template>

  <my-nav :items="[
  {'icon': 'User', 'label': '员工管理'},
  {'icon': 'User', 'label': '员工列表'},
]"/>

  <my-head :items="[
  {'type': 'ipt', 'span': 5, 'placeholder': '真实姓名', 'fn': pageByRealName},
  {'type': 'insertBtn', 'offset': 16, 'fn': () => router.push('/EmpInsert')},
  {'type': 'deleteBtn', 'fn': removeBatch},
  {'type': 'excelBtn', 'fn': () => excelApi('/emp/excel', '员工统计表')},
]"/>

  <my-table v-if="records" :records="records" :columns="[
    {'column': '员工头像', 'property': 'avatar', 'type':'img',
      minio: url => MINIO_HOST + '/avatar/' + url},
    {'column': '登录账号', 'property': 'username'},
    {'column': '真实姓名', 'property': 'realname'},
    {'column': '所在部门', 'property': 'dept.title'},
    {'column': '手机号码', 'property': 'phone'},
    {'column': '微信号码', 'property': 'wechat'},
    {'column': '电子邮件', 'property': 'email'},
    {'column': '员工性别', 'property': 'gender','format': genderFormat, 'type': 'tag'},
    {'column': '员工年龄', 'property': 'age', 'type': 'tag', 'tagType': 'info'},
    {'column': '所在省份', 'property': 'province'},
    {'column': '详细地址', 'property': 'address', 'type': 'card'},
    {'column': '身份证号', 'property': 'idcard'},
    {'column': '入职日期', 'property': 'hiredate', 'format': dateFormat},
    {'column': '创建时间', 'property': 'created', 'format': dateFormat},
    {'column': '修改时间', 'property': 'updated', 'format': dateFormat},
    {'column': '员工描述', 'property': 'info', 'type': 'card'},
]" :buttons="[
  {'type': 'info', 'fn': detail},
  {'type': 'update', 'fn': update},
  {'type': 'delete', 'fn': remove},
  {'type': 'upload', 'btnLabel': '上传头像', 'fn': upload},
  {'btnLabel': '重置密码', 'btnIcon': 'delete', 'btnType': 'danger', 'fn': resetPassword},
  {'btnLabel': '我的角色', 'btnIcon': 'User', 'btnType': 'warning', 'fn': toEmpRoles},
]" :selection-change="rows => ids = rows.map(e => e['id'])"/>

  <my-pager v-if="records" :page-info="pageInfo"/>

  <el-drawer v-model="detailDrawer" size="30%">
    <my-list title="记录详情" :items="detailItems"/>
  </el-drawer>

  <el-drawer v-model="uploadDrawer" title="上传头像" size="55%">
    <my-uploader :action="uploadUrl" name="avatarFile" :fn="uploadSuccess"/>
  </el-drawer>


</template>

<style scoped lang="scss">

</style>